<!--
 * @Descripttion: 设备维修表单
 * @LastEditors: xzh
 * @LastEditTime: 2024-06-10 15:35:14
-->
<template>
  <el-form
    ref="formRef"
    class="el-form-card"
    :model="repairRecordForm.formData"
    :rules="formRules"
    label-width="7rem"
    size="large"
    status-icon
  >
    <!-- 设备信息 -->
    <el-card>
      <template #header>
        <span>{{ $t("page.equipManageArr.equipArchivesArr.equipInfo") }}</span>
      </template>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipManageArr.equipArchivesArr.name')"
          prop="relEquip.name"
        >
          <el-input
            v-model="repairRecordForm.formData.relEquip.name"
            readonly
            :placeholder="$t('common.select')"
            @click="() => dileSelectItemTableRef.init()"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('page.equipManageArr.equipArchivesArr.code')">
          <el-input
            v-model="repairRecordForm.formData.relEquip.code"
            disabled
            :placeholder="$t('common.systemAutoGenerate')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipManageArr.equipArchivesArr.specification')"
        >
          <el-input
            v-model="repairRecordForm.formData.relEquip.specification"
            disabled
            :placeholder="$t('common.systemAutoBringOut')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('page.equipManageArr.equipType')">
          <el-input
            v-model="repairRecordForm.formData.relEquip.extJson.typeName"
            disabled
            :placeholder="$t('common.systemAutoBringOut')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('page.systemManageArr.position')">
          <el-input
            v-model="repairRecordForm.formData.relEquip.extJson.positionName"
            disabled
            :placeholder="$t('common.systemAutoBringOut')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipManageArr.equipArchivesArr.factory')"
        >
          <el-input
            v-model="repairRecordForm.formData.relEquip.extJson.factoryName"
            disabled
            :placeholder="$t('common.systemAutoBringOut')"
          />
        </el-form-item>
      </el-col>
    </el-card>
    <!-- 故障信息 -->
    <el-card>
      <template #header>
        <span>{{ $t("page.equipRepairArr.repairRecordArr.faultInfo") }}</span>
      </template>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.faultDate')"
        >
          <el-date-picker
            v-model="repairRecordForm.formData.faultDate"
            type="datetime"
            :placeholder="$t('common.selectDateTime')"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.degreeUrgency')"
        >
          <el-select
            v-model="repairRecordForm.formData.degreeUrgency"
            :placeholder="$t('common.select')"
          >
            <el-option
              v-for="degreeUrgency in Object.keys(degreeUrgencyEnum)"
              :key="degreeUrgency"
              :label="
                $t(
                  `page.equipRepairArr.repairRecordArr.degreeUrgencyArr.${degreeUrgency}`
                )
              "
              :value="degreeUrgency"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('page.equipRepairArr.faultType')">
          <!-- 输入框选择对象 -->
          <DileInputSelectItem
            v-model="repairRecordForm.formData.faultType"
            :expand-on-click-node="false"
            :selectType="selectTypeEnum.equipFaultType"
            :cacheLabel="repairRecordForm.formData.extJson.faultTypeName"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('page.equipRepairArr.repairRecordArr.isStop')">
          <el-checkbox
            v-model="repairRecordForm.formData.isShutdown"
          ></el-checkbox>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.faultDesc')"
        >
          <el-input
            v-model="repairRecordForm.formData.faultDesc"
            :rows="5"
            type="textarea"
          />
        </el-form-item>
      </el-col>
    </el-card>
    <!-- 维修信息 -->
    <el-card>
      <template #header>
        <span>{{ $t("page.equipRepairArr.repairRecordArr.repairInfo") }}</span>
      </template>
      <el-col :span="12">
        <el-form-item :label="$t('page.equipRepairArr.repairRecordArr.code')">
          <el-input
            v-model="repairRecordForm.formData.code"
            disabled
            :placeholder="$t('common.systemAutoGenerate')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.name')"
          prop="name"
        >
          <el-input
            v-model="repairRecordForm.formData.name"
            :placeholder="$t('common.enter')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.repairLevel')"
        >
          <el-select
            v-model="repairRecordForm.formData.level"
            :placeholder="$t('common.select')"
          >
            <el-option
              v-for="repairLevel in Object.keys(repairLevelEnum)"
              :key="repairLevel"
              :label="
                $t(
                  `page.equipRepairArr.repairRecordArr.repairLevelArr.${repairLevel}`
                )
              "
              :value="repairLevel"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('page.equipRepairArr.repairRecordArr.team')">
          <!-- 输入框选择对象 -->
          <DileInputSelectItem
            v-model="repairRecordForm.formData.teamId"
            :expand-on-click-node="false"
            :selectType="selectTypeEnum.team"
            :cacheLabel="repairRecordForm.formData.extJson.teamName"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.manager')"
        >
          <!-- 输入框选择对象 -->
          <DileInputSelectItem
            v-model="repairRecordForm.formData.manager"
            :selectType="selectTypeEnum.people"
            :cacheLabel="repairRecordForm.formData.extJson.managerName"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.startDate')"
          prop="startDate"
        >
          <el-date-picker
            v-model="repairRecordForm.formData.startDate"
            type="datetime"
            :placeholder="$t('common.selectDateTime')"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="
              (time:any) => dayjs(time).isAfter(repairRecordForm.formData.endDate)
            "
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.endDate')"
          prop="endDate"
        >
          <el-date-picker
            v-model="repairRecordForm.formData.endDate"
            type="datetime"
            :placeholder="$t('common.selectDateTime')"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="
              (time:any) => dayjs(time).isBefore(repairRecordForm.formData.startDate)
            "
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.recordStatus')"
        >
          <el-select
            v-model="repairRecordForm.formData.workOrderStatus"
            :placeholder="$t('common.select')"
          >
            <el-option
              v-for="recordStatus in Object.keys(repairRecordStatusEnum)"
              :key="recordStatus"
              :label="
                $t(
                  `page.equipRepairArr.repairRecordArr.repairRecordStatusArr.${recordStatus}`
                )
              "
              :value="recordStatus"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.personnels')"
        >
          <!-- 输入框选择对象 -->
          <DileInputSelectItem
            v-model="repairRecordForm.formData.personnels"
            :selectType="selectTypeEnum.people"
            :cacheLabel="repairRecordForm.formData.extJson.personnelsName"
            multiple
          />
        </el-form-item>
      </el-col>
    </el-card>
    <!-- 更换备件 -->
    <el-card>
      <template #header>
        <span>{{ $t("page.equipRepairArr.repairRecordArr.changeSpare") }}</span>
      </template>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.isReplace')"
        >
          <el-radio-group v-model="repairRecordForm.formData.isReplace">
            <el-radio :label="true">{{ $t("common.yes") }}</el-radio>
            <el-radio :label="false">{{ $t("common.no") }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.deliveryNoteCode')"
        >
          <el-input
            v-model="repairRecordForm.formData.recipientCode"
            disabled
            :placeholder="$t('common.systemAutoGenerate')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.deliveryName')"
        >
          <el-input
            v-model="repairRecordForm.formData.recipientName"
            :placeholder="$t('common.enter')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('page.systemManageArr.storeManageArr.name')">
          <!-- 输入框选择对象 -->
          <DileInputSelectItem
            v-model="repairRecordForm.formData.warehouseId"
            :expand-on-click-node="false"
            :selectType="selectTypeEnum.store"
            :cacheLabel="repairRecordForm.formData.extJson.warehouseName"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.deliveryReason')"
        >
          <el-select
            v-model="repairRecordForm.formData.recipientReason"
            :placeholder="$t('common.select')"
          >
            <el-option
              v-for="recipientReason in Object.keys(recipientReasonEnum)"
              :key="recipientReason"
              :label="
                $t(
                  `page.equipRepairArr.repairRecordArr.recipientReasonArr.${recipientReason}`
                )
              "
              :value="recipientReason"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          :label="$t('page.equipRepairArr.repairRecordArr.deliveryDate')"
        >
          <el-date-picker
            v-model="repairRecordForm.formData.recipientDate"
            type="datetime"
            :placeholder="$t('common.selectDateTime')"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-col>
    </el-card>
    <!-- 备件明细 -->
    <el-card>
      <template #header>
        <span>{{ $t("page.equipRepairArr.spareDetails") }}</span>
      </template>
      <!-- 关联备件明细 -->
      <RelSpareTable ref="relSpareTableRef">
        <template #extClounm>
          <vxe-column width="200">
            <template #header>
              <span :style="{ color: 'red' }">*</span>
              <span>{{ $t("page.equipSpareArr.spareLedgerArr.useNum") }}</span>
            </template>
            <template #default="{ row }">
              <el-input-number
                v-model="row.recipientNumber"
                controls-position="right"
                :min="0"
                size="default"
              />
            </template>
          </vxe-column>
        </template>
      </RelSpareTable>
    </el-card>
  </el-form>
  <!-- 选择对象列表 -->
  <DileSelectItemTable
    ref="dileSelectItemTableRef"
    :selectTableType="selectTableTypeEnum.equip"
    :selectedKeys="[repairRecordForm.formData.equipmentId].filter((x) => !!x)"
    :multiple="false"
    @sure="handleEquipSelected"
  />
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, nextTick, toRef } from "vue";
import type { object_Inf } from "@/utils/typings/index.type";
import { useI18n } from "vue-i18n";
import { ElNotification, dayjs } from "element-plus";
import {
  selectTableTypeEnum,
  selectTypeEnum,
} from "@/components/dile-selectItem/index.type";
import {
  degreeUrgencyEnum,
  repairLevelEnum,
  repairRecordStatusEnum,
  recipientReasonEnum,
} from "@/utils/typings/equipManage/equipRepair/index.type";
import DileInputSelectItem from "@/components/dile-selectItem/selectItem-input/index.vue";
import DileSelectItemTable from "@/components/dile-selectItem/selectItem-table/index.vue";
import RelSpareTable from "@/views/equipManage/equipSpare/spareLedger/spareLedger-relTable/index.vue";
import Dile_APi from "@/api";

const emit = defineEmits(["refresh"]);

let { t } = useI18n();
/**
 * @Author: xzh
 * @Descripttion: 选择对象表格实例
 * @Param:
 */
let dileSelectItemTableRef = ref<any>(null);
/**
 * @Author: xzh
 * @Descripttion: 关联备件表格实例
 * @Param:
 */
let relSpareTableRef = ref<any>(null);

/**
 * @Author: xzh
 * @Descripttion: 表单默认数据
 * @Param:
 */
let getDefaultData = (data: object_Inf = {}) => ({
  id: 0,
  status: true, //状态
  equipmentId: null,
  //设备信息
  relEquip: {
    name: "", //设备名称
    code: "", //设备编码
    specification: "", //规格型号
    extJson: {
      factoryName: "", //所在工厂名称
      typeName: "", //设备类型名称
      positionName: "", //存放位置
    },
  },
  //故障信息
  faultId: null, //故障主键
  faultDate: "", //故障时间
  faultDesc: "", //故障描述
  degreeUrgency: "", //紧急程度
  faultType: null, //故障类型
  isShutdown: false, //是否停机
  //维修信息
  code: "", //工单编号
  name: "", //工单主题
  level: "", //维修级别
  teamId: null, //维修班组
  manager: null, //维修负责人
  startDate: "", //维修开始时间
  endDate: "", //维修结束时间
  workOrderStatus: repairRecordStatusEnum.offDuty, //工单状态
  personnels: "", //其他维修人员
  //更换备件
  isReplace: false, //是否更换备件
  recipientCode: "", //领用单号
  recipientName: "", //领用主题
  warehouseId: null, //仓库
  recipientReason: "", //领用原因
  recipientDate: "", //领用时间
  extJson: {
    faultTypeName: "", //故障类型名称
    teamName: "", //维修班组名称
    managerName: "", //维修负责人名称
    personnelsName: "", //其他维修人员名称
    warehouseName: "", //仓库名称
  },
  ...data,
});
/**
 * @Author: xzh
 * @Descripttion: 保养计划表单参数
 * @Param:
 */
let repairRecordForm = reactive<object_Inf>({
  //表单数据
  formData: getDefaultData(),
  resoure: {
    //设备状态
    equipStateArr: [],
    //设备存放位置
    equipPositionArr: [],
  },
});

/**
 * @Author: xzh
 * @Descripttion: 表单实例
 * @Param:
 */
let formRef = ref<any>(null);

/**
 * @Author: xzh
 * @Descripttion:表单验证规则
 * @Param:
 * @param {*} computed
 */
let formRules = computed((): any => {
  return reactive({
    ["relEquip.name"]: [
      {
        required: true,
        message:
          t("common.enter") + t("page.equipManageArr.equipArchivesArr.name"),
        trigger: "change",
      },
    ],
    name: [
      {
        required: true,
        message:
          t("common.enter") + t("page.equipRepairArr.repairRecordArr.name"),
        trigger: "change",
      },
    ],
    startDate: [
      {
        required: true,
        message:
          t("common.select") +
          t("page.equipRepairArr.repairRecordArr.startDate"),
        trigger: "change",
      },
    ],
    endDate: [
      {
        required: true,
        message:
          t("common.select") + t("page.equipRepairArr.repairRecordArr.endDate"),
        trigger: "change",
      },
    ],
  });
});

/**
 * @Author: xzh
 * @Descripttion: 加载表单数据
 * @Param:
 */
let initFormData = async (id: number, defaultData: object_Inf = {}) => {
  let { model, dataList, equipmentModel, relations }: object_Inf = !!id
    ? await Dile_APi.getEquipRepairRecordInfo(id)
    : { model: getDefaultData(defaultData) };

  Object.assign(repairRecordForm.formData, {
    ...model,
    relEquip: { ...model.relEquip, ...equipmentModel },
  });
  //格式化关联备件信息
  if (dataList?.length > 0) {
    let relSpareArr = dataList
      .map((spare: object_Inf) => {
        let { id, recipientNumber } = relations?.find(
          (x: object_Inf) => x.sparePartId == spare.id
        );
        return !!id
          ? {
              ...spare,
              recipientNumber,
              relId: id,
            }
          : {};
      })
      .filter((x: object_Inf) => !!x.id);
    //加载关联备件表格
    relSpareTableRef.value.initTableData(relSpareArr);
  }
};

/**
 * @Author: xzh
 * @Descripttion: 设备选中事件
 * @Param:
 * @param {*} equip
 */
let handleEquipSelected = (equipArr: Array<object_Inf>) => {
  let { formData } = toRefs(repairRecordForm),
    equip: object_Inf = equipArr.find(() => true) || {};
  Object.assign(formData.value, {
    ...formData.value,
    equipmentId: equip.id,
    relEquip: equip,
  });
};
/**
 * @Author: xzh
 * @Descripttion: 保存事件
 * @Param:
 */
let hanldeSaveForm = async () => {
  let { formData } = repairRecordForm,
    valid = await formRef.value.validate();
  //表单验证&&关联备件验证
  if (!valid || !verifyRelSpare()) {
    return false;
  }

  let { id, startDate, endDate } = formData,
    relData: object_Inf = relSpareTableRef.value.getRelData();
  //格式化关联设备信息
  Object.keys(relData)
    .filter((x) => x != "deleteRelations")
    .forEach(
      (relkey) =>
        (relData[relkey] = relData[relkey].map((x: object_Inf) => {
          let { id: sparePartId, recipientNumber, relId } = x;
          return {
            id: relId,
            repairRecordId: id,
            sparePartId,
            recipientNumber,
          };
        }))
    );
  let data = await Dile_APi.saveEquipRepairRecord({
    model: {
      ...formData,
      //计算时长
      totalDuration: dayjs(endDate).diff(dayjs(startDate), "day"),
    },
    ...relData,
  });
  //触发刷新回调
  emit("refresh", data);
  //提示成功
  ElNotification({
    message: t("common.message.OperationSuccess"),
    type: "success",
  });
  return data;
};

/**
 * @Author: xzh
 * @Descripttion: 验证关联备件
 * @Param:
 */
let verifyRelSpare = () => {
  let relSpareData: object_Inf = relSpareTableRef.value.getTableData();
  //获取备件数量为空数组
  let emptyUserNumArr = relSpareData.filter(
    (x: object_Inf) => !!x.id && !x.recipientNumber
  );
  if (emptyUserNumArr.length > 0) {
    ElNotification({
      message: `[${emptyUserNumArr
        .map((x: object_Inf) => x.name)
        .join(",")}]:${t("common.enter")}${t(
        "page.equipSpareArr.spareLedgerArr.useNum"
      )}`,
      type: "warning",
    });
    return false;
  }
  return true;
};

defineExpose({
  hanldeSaveForm,
  initFormData,
});
</script>
<style lang="scss" scoped></style>
